let wxMarkerData = [];    //  定位成功回调对象
let bmap = require('../libs/bmap-wx.min.js');

var app = getApp()    
Page({
  data: {
    ak:"gSGgviuSsGGF9iiqOpXIuloUKwjauBbf",      //  ak
    markers:[],
    longitude:'',     //  经度
    latitude:'',        //  纬度
    address:'',       //  地址
    cityInfo:{},      //  城市信息
    distance:0, // 距离
    merchant:[] // 附近商家
  },
  getLocation(){
    wx.navigateTo({
      url: '/pages/position/index',
    })
  },
  // 跳转订单
  order(data){
    let name = data.currentTarget.dataset.name
    let index = data.currentTarget.dataset.inx
    this.setData({
      distance : this.data.merchant[index].distance
    })
    let datas={
      name:name,
      latitude : this.data.latitude,
      longitude : this.data.longitude,
      distance : this.data.distance // 距离
    }
    app.globalData.datasTack = datas;
    wx.reLaunch({
      url: '../index/index?name=tack',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  gohome:function(){
    wx.navigateBack({
      delta:1
    })
  },
  onLoad: function (options) {
    this.Shops()
  },
  Shops(){
    var that = this;
    let BMap = new bmap.BMapWX({
      ak:that.data.ak
    });
    let fail = function(data){
      console.log(data);
    };
    let success = function(data){
      // 返回数据内，已经包含经纬度
      // 使用wxMarkerData获取数据
      wxMarkerData = data.wxMarkerData;
      // 把所有数据放在初始化data内
      that.setData({
        markers:wxMarkerData,
        latitude: wxMarkerData[0].latitude,
        longitude: wxMarkerData[0].longitude,
        address:wxMarkerData[0].address,
        cityInfo:data.originalData.result.addressComponent
      });
    that.NearTheShop(that.data.latitude,that.data.longitude); // 商家的位置获取
    };
    // 发起regeocoding检索请求
    BMap.regeocoding({
      fail:fail,
      success:success
    });
  },
  NearTheShop(latit,long){
    var that = this
    wx.request({
      url: `http://localhost:8081/interfaced/shop/list?shopLongitude=${long}&shopLatitude=${latit}`,
      success(data){
        that.merchants(data.data.rows)
      }
    })
  },
  merchants(data) {
    for (let a = 0; a < data.length; a++) {
      var m = this.getDistance(this.data.latitude, this.data.longitude, data[a].shopLatitude, data[a].shopLongitude)
      data[a].distance = m // 距离
    }

    this.setData({
      merchant: data
    })
  },
  Rad(d) {
    //根据经纬度判断距离
    return d * Math.PI / 180.0;
  },
  getDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = this.Rad(lat1);
    var radLat2 = this.Rad(lat2);
    var a = radLat1 - radLat2;
    var b = this.Rad(lng1) - this.Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = (s*1000).toFixed(2) + 'm' //保留两位小数
    return s
  }
})